import axios from 'axios'

import { Toast } from 'vant'

import store from '@/store'

import { getTimeStamp } from '@/utils/auth'

import router from '@/router'

const time = 10000

const service = axios.create({
  daseURL: 'http://127.0.0.1:3000',
  timeout: 10000

})

// 添加请求拦截器
service.interceptors.request.use(function(config) {
  // 在发送请求之前做些什么
  if (!config.headers.Authorization && store.getters.token) {
    if (!isTimeOut()) {
      config.headers.Authorization = `Bearer ${store.getters.token}`
    } else {
      router.push('/login?redirect=' + location.hash.substr(1))
      Toast.fail('登录超时')
      return Promise.reject(new Error('登录超时'))
    }
  }
  return config
}, function(error) {
  // 对请求错误做些什么
  Toast.fail('请求错误')
  return Promise.reject(new Error(error.message))
})

// 添加响应拦截器
service.interceptors.response.use(function(response) {
  // 对响应数据做点什么
  return response
}, function(error) {
  // 对响应错误做点什么
  return Promise.reject(new Error(error.message))
})

function isTimeOut() {
  const currentTime = Date.now()

  const timeStamp = getTimeStamp()

  return (currentTime - timeStamp) / 1000 > time
}

export default service
